import parser

from precommit import PreCommitChecker

class Application(PreCommitChecker):

    def check_file(self, filename, lines):
        """Check the file to see if it tokenizes correctly"""
        try:
            parser.suite("".join(lines))
        except SyntaxError, e:
            self.error_recorder.add(filename, self.syntax_error(filename, e))
        except Exception, e:
            self.error_recorder.add(filename, self.unknown_error(filename, e))

    def syntax_error(self, filename, exc):
        message = """File "%(filename)s", line %(lineno)s
%(text)s%(pointer)s
SyntaxError: %(msg)s
"""
        def pointer():
            return " " * max(exc.offset-1, 0) + "^"
        
        subst = dict(filename=filename,
                     lineno=exc.lineno,
                     text=exc.text,
                     pointer=pointer(),
                     msg=exc.msg)
        return message % subst

    def unknown_error(self, filename, exc):
        return "Exception: %s" % str(exc)